package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class FriendApiImpl implements FriendApi{
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void save(Long frindId, Long userId) {
        Query query =Query.query(Criteria.where("userId").is(userId).and("friendId").is( frindId));
        if(!mongoTemplate.exists(query,Friend.class)){//如果不存在添加好友数据
            Friend friend1 =new Friend();
            friend1.setUserId(userId);
            friend1.setFriendId(frindId);
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }
        Query query1 =Query.query(Criteria.where("userId").is(frindId).and("friendId").is(userId));
        if(!mongoTemplate.exists(query1,Friend.class)){//如果不存在添加好友数据
            Friend friend2 =new Friend();
            friend2.setUserId(frindId);
            friend2.setFriendId(userId);
            friend2.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend2);
        }
    }

    @Override
    public List<Long> findByFriendId(Long userId) {
        Query query =Query.query(Criteria.where("friendId").is(userId));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        List<Long> list =new ArrayList<>();
        for (Friend friend : friends) {
            if (friend.getUserId()!=null){
                list.add(friend.getUserId());
            }
        }
        return list;
    }

    @Override
    public void deleteFriend(Long userId, Long likeUserId) {
        Query query =Query.query(Criteria.where("userId").is(userId).and("friendId").is(likeUserId));
        Query query1 =Query.query(Criteria.where("userId").is(likeUserId).and("friendId").is(userId));
        mongoTemplate.remove(query,Friend.class);
        mongoTemplate.remove(query1,Friend.class);
    }

    @Override
    //查找好友的所有数据
    public List<Long> findById(int page, int pagesize, Long userId) {
        Query query=Query.query(Criteria.where("userId").is(userId)).skip((page-1)*pagesize).limit(pagesize);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        List<Long> userIds = CollUtil.getFieldValues(friends, "friendId", Long.class);
        return  userIds;

    }
